package com.zhongxi.guoyuan.view.personalCenter;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.UpdateResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.ClearCacheUtils;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.user.FeedBackActivity;
import com.zhongxi.guoyuan.view.user.UserInfoSettingActivity;

import java.io.File;

public class SettingActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout relaFeedBack;
    private RelativeLayout relaUserInfo;
    private RelativeLayout relaUpdate;
    private ProgressDialog pb;
    private String UPDATE_SAVENAME = "/meirongyuan";
    private RelativeLayout relaExit;
    private RelativeLayout relaMessage;
    private RelativeLayout relaDynamics;
    private ImageView ivHead;
    private UpdateResult result;
    private TextView tvCache;
    private RelativeLayout relaClear;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_setting);
        initTitle();
        tvTitle.setText("设置");
        relaFeedBack = (RelativeLayout) findViewById(R.id.relaFeedBack);
        relaUserInfo = (RelativeLayout) findViewById(R.id.relaUserInfo);
        relaUpdate = (RelativeLayout) findViewById(R.id.relaUpdate);
        relaExit = (RelativeLayout) findViewById(R.id.relaExit);
        relaMessage = (RelativeLayout) findViewById(R.id.relaMessage);
        relaClear = (RelativeLayout) findViewById(R.id.relaClear);
        relaDynamics = (RelativeLayout) findViewById(R.id.relaDynamics);
        ivHead = (ImageView) findViewById(R.id.ivHead);
        tvCache = (TextView) findViewById(R.id.tvCache);

        if(null!=MyApplication.getInstance().getAvatar()&&!"".equals(MyApplication.getInstance().getAvatar())){
            Glide.with(context).load(Url.BASE_URL+MyApplication.getInstance().getAvatar()).placeholder(R.mipmap.logo).transform(new GlideRoundTransform(context, 20)).into(ivHead);
        }

        try{
            if(ClearCacheUtils.getTotalCacheSize(this)!=null){
                tvCache.setText(ClearCacheUtils.getTotalCacheSize(this).toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        relaFeedBack.setOnClickListener(this);
        relaUpdate.setOnClickListener(this);
        relaUserInfo.setOnClickListener(this);
        relaExit.setOnClickListener(this);
        relaMessage.setOnClickListener(this);
        relaDynamics.setOnClickListener(this);
        relaClear.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.relaUserInfo:
                startAct(UserInfoSettingActivity.class);
                break;
            case R.id.relaMessage:
                startAct(SystemMessageActivity.class);
                break;
            case R.id.relaDynamics:
                startAct(DynamicsActivity.class);
                break;
            case R.id.relaFeedBack:
                startAct(FeedBackActivity.class);
                break;
            case R.id.relaClear:
                ClearCacheUtils.clearAllCache(this);
                showShortToast("清理完成");
                tvCache.setText("0KB");
                break;
            case R.id.relaUpdate:
                getServer(Url.CHECK_UPD, null, "", false, null, "get");
                break;
            case R.id.relaExit:
                if(null!=MyApplication.getInstance().getUserId()||!"".equals(MyApplication.getInstance().getUserId())){
                    SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
                    sharedPrefrences.edit().putString("phone", "").commit();
                    sharedPrefrences.edit().putString("userid", "").commit();
                    sharedPrefrences.edit().putString("username", "").commit();
                    sharedPrefrences.edit().putString("shopname", "").commit();
                    sharedPrefrences.edit().putString("rmb", "").commit();
                    sharedPrefrences.edit().putString("silver", "").commit();
                    sharedPrefrences.edit().putString("inner", "").commit();
                    sharedPrefrences.edit().putString("num", "").commit();
                    sharedPrefrences.edit().putString("avatar", "").commit();
                    sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
                    sharedPrefrences.edit().putBoolean("privilege", false).commit();
                    startAct(MainHomeActivity.class);
                    finish();
                }
                break;
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            result = gson.fromJson(response, UpdateResult.class);
            if(null!=result.getUpdClient()&&!"".equals(result.getUpdClient())){
                if(null!=result.getUpdClient().getDownUrl()&&!"".equals(result.getUpdClient().getDownUrl())){
                    downFile();
                }else{
                    showShortToast("暂无更新");
                }
            }else {
                showShortToast("暂无更新");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try{
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if(null!=result.getSafeobj()&&null!=result.getSafeobj()){
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void downFile() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("版本升级");
        if(null!=result.getUpdClient().getDesc()&&!"".equals(result.getUpdClient().getDesc())){
            builder.setMessage(result.getUpdClient().getDesc());
        }else{
            builder.setMessage("修复bug，并添加新模块");
        }
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                downLoadApk();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 下载APK
     */
    private void downLoadApk() {
        final ProgressDialog pd; //进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(1000);
        pd.setMessage("正在下载更新");
        pd.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = CommonTool.getFileFromServer(result.getUpdClient().getDownUrl(), pd);
                    installApk(file);
                    pd.dismiss();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }

}
